package com.itheima.reggie.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
//    @Autowired
//    ShoppingController shoppingController;
    @Autowired
    OrdersService ordersService;
    @Autowired
    OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R submitOrder(@RequestBody Orders orders){
        ordersService.submitOrderService(orders);
        return R.success("");
    }

    @Transactional
    @GetMapping("/userPage")
    public R selectOrder(Integer page,Integer pageSize){
        Page<OrdersDto> p= new Page(page,pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, UserHolder.getUser().getId());
        List<Orders> list_orders = ordersService.list(lqw);

        List<OrdersDto> list_ordersDto = list_orders.stream().map((orders) -> {
            LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
            lqw1.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailService.list(lqw1);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());

        p.setRecords(list_ordersDto);

        return R.success(p);
    }
}
